from django_redis import get_redis_connection
from rest_framework import serializers
import logging

logger = logging.getLogger('meiduo')


class RegisterSmsCodeSerializer(serializers.Serializer):


    text = serializers.CharField(label='用户输入的验证码', max_length=4, min_length=4, required=True)

    image_code_id = serializers.UUIDField(label='uuid')


    def validate(self, attrs):

        # 1.获取用户提交的验证码和uuid
        text = attrs.get('text')
        image_code_id = attrs.get('image_code_id')

        #  2.链接redis,获取redis中的验证码
        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('img_%s' % image_code_id)

        #  3.判断从redis中获取的验证码是否过期
        if not redis_text:
            raise serializers.ValidationError('验证码已过期')

        # 4.将redis中的验证码删除,记录异常
        try:
            redis_conn.delete('img_%s' % image_code_id)
        except Exception as e:
            logger.error(e)

        # 5.将用户输入的验证码和redis中的验证码进行比较
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('验证码错误')

        return attrs



